/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.controller
 * 创建时间：2020年03月16日 12时47分
 **/
package com.zhongwang.mms.module.purchase.controller;

import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.config.timingtask.StatisticalTimingTask;
import com.zhongwang.mms.gen.entity.Role;
import com.zhongwang.mms.gen.entity.TCost;
import com.zhongwang.mms.gen.entity.TWarehouseInfo;
import com.zhongwang.mms.module.basic.dao.TCostDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.buy.dao.PurchaseDao;
import com.zhongwang.mms.module.purchase.constant.PurchaseConstant;
import com.zhongwang.mms.module.purchase.model.PInOrder;
import com.zhongwang.mms.module.purchase.model.PurWarInManageParamModel;
import com.zhongwang.mms.module.purchase.model.VWProject;
import com.zhongwang.mms.module.purchase.service.PurWarInManageService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.module.system.role.RoleModel;
import com.zhongwang.mms.module.system.role.RoleService;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;


/**
 * @ClassName： PurWarInManageController
 * @Description： 外购件入库控制层
 * @Author： 徐一贺
 * @Date： 2020/3/16 12:47
 * @Version： V1.0
 **/
@Controller
@RequestMapping("/purWarInManage")
public class PurWarInManageController extends BaseController {

    @Autowired
    private PurWarInManageService purWarInManageService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private BoardService boardService;

    @Autowired
    private TCostDao tCostDao;

    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;

    @Autowired
    private LogService logService;
    /**
     * 正式入库页面
     *
     * @return 页面路径
     */
    @GetMapping("/index/{mode}")
    @RequiresPermissions(value={"purwar:purinwar:view","mecwar:inwar:view","ykwar:inwar:view"},logical= Logical.OR)
    public String PurWarInManage(Model model, @PathVariable("mode") String mode) {
        model.addAttribute("mode", mode);
        //获取角色码用来进行控制页面显示内容
        List<Role> roles = new ArrayList<>();
        roles.addAll(roleService.findRolesByUserId(ShiroUtils.getUser().getId()));
        List<String> roleCodes = new ArrayList<>();
        for (Role role:roles) {
            if(role.getRoleCode().equals("W01")){
                roleCodes.add(role.getRoleCode());
            }else if(role.getRoleCode().equals("W02")){
                roleCodes.add(role.getRoleCode());
            }else if(role.getRoleCode().equals("W03")){
                roleCodes.add(role.getRoleCode());
            }
        }
        if(ShiroUtils.getUser().getAccount().equals("admin")){
            roleCodes.add("admin");
        }
        model.addAttribute("roleCodes", roleCodes);
        model.addAttribute("odrMakePerson", ShiroUtils.getUser().getName());
//        String serialNumber = ShiroUtils.getUser().getAccount()+UUID.randomUUID().toString();
//        ShiroUtils.getUser().setSerialNumber(serialNumber);
//        model.addAttribute("serialNumber", serialNumber);
        return "purchase/purWarManage/PurWarInManage/page";
    }


    @PostMapping("/getWarInOrderCode")
    @ResponseBody
    @RequiresPermissions(value={"purwar:purinwar:view","mecwar:inwar:view","ykwar:inwar:view"},logical=Logical.OR)
    /**
     *@FunctionName: getOrderCode
     *@Description: 获取最新的入库编号
     *@Author: 徐一贺
     *@CreateDate: 2020/3/23 7:55
     *@Phone: 18241927380
     *@Param: []
     *@Return: com.zhongwang.mms.common.JsonResult
     *@Version:
     */
    public JsonResult getWarInOrderCode(PurWarInManageParamModel param) {
        //获取入库单单据编号
        String orderCode = purWarInManageService.getOrderCode(PurchaseConstant.PRK);
        if (param.getOdrCode() != null && param.getOdrCode().equals(orderCode)) {
            return JsonResult.success("FAIL", orderCode);
        }
        return JsonResult.success("SUCCESS", orderCode);
    }


    @PostMapping("/create")
    @ResponseBody
    @RequiresPermissions(value={"purwar:purinwar:edit","mecwar:inwar:edit","ykwar:inwar:edit"},logical=Logical.OR)
    /**
     *@FunctionName: create
     *@Description: 创建入库单
     *@Author: 徐一贺
     *@CreateDate: 2020/3/23 10:46
     *@Phone: 18241927380
     *@Param: [pInOrder] 入库数据
     *@Return: com.zhongwang.mms.common.JsonResult 返回结果
     *@Version: 1.0.0
     */
    public JsonResult create(@RequestBody PInOrder pInOrder) {
        String res = "";
        JsonResult jsonResult = new JsonResult();
        List<String> result = new ArrayList<>();
        List<VWProject> vWProjectList = StatisticalTimingTask.VWProjectCache;
        List<String> codes = new ArrayList<>();
        for (VWProject vWProject:vWProjectList) {
            if(!codes.contains(vWProject.getCode())){
                codes.add(vWProject.getCode().toUpperCase());
            }
        }
        try {
            for (int i = 0; i < pInOrder.getInsertData().size(); i++) {
                if (pInOrder.getInsertData().get(i).getOdaMatDesc() == null || pInOrder.getInsertData().get(i).getOdaMatDesc() == "") {
                    result.add("\n第" + (i + 1) + "行" + " 物料描述 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaNum() == null || pInOrder.getInsertData().get(i).getOdaNum() <= 0) {
                    result.add("\n第" + (i + 1) + "行" + " 数量为空或为负数 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaNumUnit() == null || pInOrder.getInsertData().get(i).getOdaNumUnit() == "") {
                    result.add("\n第" + (i + 1) + "行" + " 单位为空 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaTotalPrice() == null || pInOrder.getInsertData().get(i).getOdaTotalPrice() < 0) {
                    result.add("\n第" + (i + 1) + "行" + " 金额为空或为负数 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaNumPrice() == null || pInOrder.getInsertData().get(i).getOdaNumPrice() < 0) {
                    result.add("\n第" + (i + 1) + "行" + " 单价为空或为负数 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaProCode() != null &&
                        pInOrder.getInsertData().get(i).getOdaProCode() != "") {
                    if (!codes.contains(boardService.projectCodeHandle(pInOrder.getInsertData().get(i).getOdaProCode()).toUpperCase())) {
                        result.add("\n第" + (i + 1) + "行" + " 项目编号【" + pInOrder.getInsertData().get(i).getOdaProCode() + "】不存在 请修改");
                    }
                    if (StringUtils.isContainChinese(pInOrder.getInsertData().get(i).getOdaProCode())) {
                        result.add("\n第" + (i + 1) + "行" + " 项目编号不可出现汉字 违规字符");
                    }
                }
                if (pInOrder.getInsertData().get(i).getWarehouseLocation() == null || pInOrder.getInsertData().get(i).getWarehouseLocation() == "") {
                    result.add("\n第" + (i + 1) + "行" + " 仓库为空 为空");
                }
                if (pInOrder.getInsertData().get(i).getOdaItyStockType() == null || Objects.equals(pInOrder.getInsertData().get(i).getOdaItyStockType(), "")) {
                    result.add("\n第" + (i + 1) + "行" + " 在库类型为空 为空");
                } else {
                    if (!pInOrder.getInsertData().get(i).getOdaItyStockType().equals("库存在库") && !pInOrder.getInsertData().get(i).getOdaItyStockType().equals("项目在库")) {
                        result.add("\n第" + (i + 1) + "行" + " 入库类型不正确，应为“库存在库”或“项目在库”。");
                    } else if (pInOrder.getInsertData().get(i).getOdaItyStockType().equals("项目在库")) {
                        if (pInOrder.getInsertData().get(i).getOdaProName() == null || Objects.equals(pInOrder.getInsertData().get(i).getOdaProName(), "")) {
                            result.add("\n第" + (i + 1) + "行" + " 项目文本为空 为空");
                        }
                        if (pInOrder.getInsertData().get(i).getOdaProCode() == null || Objects.equals(pInOrder.getInsertData().get(i).getOdaProCode(), "")) {
                            result.add("\n第" + (i + 1) + "行" + " 项目编码为空 为空");
                        }
                    }
                }
            }
            if (!result.isEmpty()) {
                result.add("\n单据保存失败！");
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setData(result);
                return jsonResult;
            }
            List<TCost> tCostList = tCostDao.selectByExample(null);
            List<TWarehouseInfo> tWarehouseInfoList = tWarehouseInfoDao.selectByExample(null);
            String code = purWarInManageService.getOrderCode(PurchaseConstant.PRK);
            res = purWarInManageService.create(pInOrder,tCostList,tWarehouseInfoList,code);
            if (res.equals("单据保存成功！")) {
                //记录操作日志
                logService.saveLog("出入库操作-入库", "入库单据编码：" + code);
                result.add("单据保存成功！");
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
                jsonResult.setData(result);
                return jsonResult;
            } else {
                result.add("单据保存失败！");
                jsonResult.setType(JsonResult.ResultType.ERROR);
                jsonResult.setData(result);
                return jsonResult;
            }
        }catch (Exception e){
            result.add("单据保存失败！");
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setData(result);
            return jsonResult;
        }
    }


//    /**
//     * 导入外购件入库单
//     *
//     * @param uploadExcelFile 导入文件
//     * @return JsonResult
//     */
//    @ResponseBody
//    @PostMapping("/import")
//    @RequiresPermissions({"board:dailyTotal"})
//    public JsonResult dailyTotalImport(@RequestParam("file") MultipartFile uploadExcelFile, HttpServletResponse response) {
//        String msg = purWarInManageService.uploadExcelFile(uploadExcelFile);
//        JsonResult jsonResult;
//        if ("上传失败".equals(msg)) {
//            jsonResult = error();
//        } else {
//            jsonResult = success();
//        }
//        jsonResult.setMsg(msg);
//        return jsonResult;
//    }
}